package util;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;


public class XMLUtil {
//	public static void readXMLFromString(String filePath) {
//		 XMLWriter writer = null;
//         SAXReader reader = new SAXReader();
//
//         OutputFormat format = OutputFormat.createPrettyPrint();
//         format.setEncoding("GBK");
//
//         String filePath = "d:\\student.xml";
//         File file = new File(filePath);
//         if (file.exists()) {
//             Document document = reader.read(file);
//             Element root = document.getRootElement();
//
//	}
	 // 从文件读取XML，输入文件名，返回XML文档
    public static Document read(String fileName) {
       SAXReader reader = new SAXReader();
       Document document = null;
	try {
		document = reader.read(new File(fileName));
	} catch (DocumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
       return document;
    }
    
    //build tree according to DOM, 
    //like the view 'outline', nodeName +　first attribut'a name and value
    public static void getFrameworkTree(Tree tree, Document doc) {
    	tree.removeAll();
    	treeWalk(tree, doc);
    }
    
    //set the root treeItem
    private static void treeWalk(Tree tree, Document doc) {
		Element rootElementDOM = doc.getRootElement();
		TreeItem rootTreeItem = new TreeItem(tree, SWT.NONE);
		rootTreeItem.setText(getTreeString(rootElementDOM));
		rootTreeItem.setExpanded(true);
		treeWalk(rootTreeItem, rootElementDOM);
    }
    
    //get the display string of treeItem
    private static String getTreeString(Element node) {
	  String attributeString = "";
	  if(node.attributeCount()>0)
		  attributeString = ((Element) node).attribute(0).getName()+"="+((Element) node).attribute(0).getText();
		return node.getName()+"  "+attributeString;
	}
    
    //walk DOM and build tree by recursion
    private static void treeWalk(TreeItem ti, Element element) {
       for (int i = 0, size = element.nodeCount(); i < size; i++)     {
           Node node = element.node(i);
           if (node instanceof Element) {
        	   TreeItem nextGeneration = new TreeItem(ti, SWT.NONE);
        	   nextGeneration.setText(getTreeString((Element) node));
        	   nextGeneration.setExpanded(true);
        	   treeWalk(nextGeneration, (Element) node);
           } else { // do something
//        	   System.out.println("kkkkkkk");
           }
       }
}
//get project model table, one row item represents one project
	public static void getProjectTable(Table table, Iterator<Element> pIterator) {
		//clear cache of the last input
		table.removeAll();
//		Element rootElementDOM = doc.getRootElement();
		 for ( ; pIterator.hasNext();) {
		       Element project = (Element) pIterator.next();
		       String[] talbleStrings = getProjectTableStrings(project);
		       TableItem item = new TableItem(table, SWT.NONE);
		       for(int j=0; j<talbleStrings.length; j++) {
		    	   item.setText(j, talbleStrings[j]);
		       }
		    }
		 
	}

	//get strings for one table item
	private static String[] getProjectTableStrings(Element project) {
		String id = project.attribute("id").getText();
		String title = "";
		String date = "";
		String duty = "";
		String subordination = "";
		String subjectCode = "";
		String grantNO = "";
		String approvedAmount = "";
		Element description = project.element("description");
		List<Element> nodes = description.elements();
		for(Element node : nodes) {
			if("title".equals(node.getName())) {
				title = node.getText();
				continue;
			}
			if("date".equals(node.getName())) {
				date = node.getText();
				continue;
			}
			if("duty".equals(node.getName())) {
				duty = node.getText();
				continue;
			}
			if("subordination".equals(node.getName())) {
				subordination = node.getText();
				continue;
			}
			if("subjectCode".equals(node.getName())) {
				subjectCode = node.getText();
				continue;
			}
			if("grantNO".equals(node.getName())) {
				grantNO = node.getText();
				continue;
			}
			if("approvedAmount".equals(node.getName())) {
				approvedAmount = node.getText();
				continue;
			}
		}
		return new String[] {id, title, date, duty, subordination, subjectCode, grantNO, approvedAmount};
	}

	public static void getMethodTable(Table table, Document doc) {
		table.removeAll();
		Element rootElementDOM = doc.getRootElement();
		 for ( Iterator i = rootElementDOM.elementIterator("method"); i.hasNext();) {
			 Element method = (Element) i.next();
			 String[] talbleStrings = getMethodTableStrings(method);
			 TableItem item = new TableItem(table, SWT.NONE);
		       for(int j=0; j<talbleStrings.length; j++) {
		    	   item.setText(j, talbleStrings[j]);
		       }
		 }
	}

	private static String[] getMethodTableStrings(Element method) {
		String name = method.attribute("name").getText();
//		String axisNum = method.attribute("axisNum").getText();
//		String projectNum = method.attribute("projectNum").getText();
		String description = method.element("description").getText();
		String input = method.element("input").getText();
		String output = method.element("output").getText();
		return new String[] {name, description, input, output};
	}

	public static List<String> getMethodScript(Document doc) {
		List<String> list = new ArrayList<String>();
		Element rootElementDOM = doc.getRootElement();
		 for ( Iterator i = rootElementDOM.elementIterator("method"); i.hasNext();) {
			 Element method = (Element) i.next();
			 list.add(getMethodScript(method));
		 }
		return list;
	}

	private static String getMethodScript(Element method) {
		String name = method.attribute("name").getText();
		String input = method.element("input").getText();
		return name+"["+input.trim()+"]";
	}
	
	public static boolean doc2XmlFile(Document document, String filename) {
		// TODO Auto-generated method stub
	    boolean flag = true; 
	      try 
	       { 
	            /* 将document中的内容写入文件中 */ 
	            //默认为UTF-8格式，指定为"GB2312" 
	             OutputFormat format = OutputFormat.createPrettyPrint(); 
	             format.setEncoding("UTF-8"); 
	             XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format); 
	             writer.write(document); 
	             writer.close();             
	         }catch(Exception ex) 
	         { 
	             flag = false; 
	             ex.printStackTrace(); 
	         } 
	        return flag;       

	}
}
